/*
    main.c
    Copyright (C) 2011  Jiabo <jiabo2011@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "global.h"
#include "loader.h"
#include "block_dev.h"
#include "hw/hardware.h"
#include "base/exec.h"
#include "hw/vga.h"

#define BIOS_FILENAME "bios.bin"
#define VGABIOS_FILENAME "vgabios.bin"

static const char *bios_dir = "./bios/";
uint8_t *phys_ram_base;

VGACommonState *vga;
BlockDriverState *bs_table[MAX_DISKS];

void host_alarm_handler(int host_signum)
{
	printf("timer arrived\n");
	vga_draw_text(vga);
}

int main(int argc, char **argv, char **envp)
{
	int ret;
	char buf[1024];

	phys_ram_base = malloc(2 * 1024 * 1024);
	if (!phys_ram_base) {
		fprintf(stderr, "Could not allocate physical memory\n");
		exit(-1);
	}
//	start_timer();

    /* open the virtual block devices */
	bs_table[2] = bdrv_open("DOS5.0.iso");
	if (!bs_table[2]) {
		fprintf(stderr, "Could not open hard disk image\n");
		exit(-1);
	}

	pc_basic_device_init();
	mc146818_init();
	bios_debug_init();
	kbd_init();
	serial_init();
	vga = vga_init(phys_ram_base + 0xb8000);
	ide_init();

//	printf("alloc memory at %p\n", phys_ram_base);
	/* BIOS load */
	snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
	ret = load_image(buf, phys_ram_base + 0x000f0000);
	if (ret != 0x10000) {
		fprintf(stderr, "Could not load PC bios '%s'\n", buf);
		exit(-1);
	}

	/* VGA BIOS load */
	snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);
	ret = load_image(buf, phys_ram_base + 0x000c0000);

	emu_start();
	
	return 0;
}

